def getMysqlMsg(jobName) {
    getDatabaseConnection(type: 'GLOBAL') {
        def result = sql(sql: "select * from job_msg where job_name=\"${jobName}\"")
        println result.size()
        if (result.size() != 1 ) {
            error "从数据库中取结果异常，数量不等一"
        }
        return result
    } 
}

def job_msg = getMysqlMsg(JOB_BASE_NAME)[0]
env.JOB_GIT_URL=job_msg.git_url
env.JOB_PORT=job_msg.job_port
env.JOB_PATH=job_msg.project_path


pipeline {
    agent any
    tools {
        maven "mvn3.3"
    }
    parameters {
        listGitBranches(
            name: 'BRANCH', 
            branchFilter: 'refs/heads/(.*)', 
            credentialsId: 'git-root', 
            defaultValue: 'master', 
            description: '你要选取哪个分支进行构建', 
            quickFilterEnabled: true, 
            remoteURL: env.JOB_GIT_URL, 
            selectedValue: 'NONE', 
            sortMode: 'NONE', 
            tagFilter: '*', 
            type: 'PT_BRANCH')
        choice(name: 'PLATFORM', choices: ['dev','qa'], description: '要部署哪个环境')
    }
    stages {
        stage('代码检出') {
            steps {
                echo '清理工作目录'
                deleteDir()
                echo '执行代码检出'
                checkout(
                    [$class: 'GitSCM', doGenerateSubmoduleConfigurations: false, submoduleCfg: [], extensions: [[$class: 'CloneOption', depth: 1, noTags: false, reference: '', shallow: true]],
                     branches: [[name: BRANCH]],userRemoteConfigs: [[url: env.JOB_GIT_URL, credentialsId: 'git-root']]]
                )
            }
        }
        stage('构建') {
            steps {
                echo '构建'
                script {
                    def statusCode = sh returnStatus: true, script: "mvn clean install" // 全局引入tools后 这里就不需要在source 环境变量文件了
                    if (statusCode!=0) {
                        error "构建出现错误！！！请开发在本地打包测试后再提交构建"
                    }
                    
                    echo '检查构建产物是否存在'
                    echo '检查产物名称是否符合规范'
                    script {
                        if (fileExists(env.JOB_PATH)){
                        	// 归档构建产物
                            archiveArtifacts artifacts: env.JOB_PATH, fingerprint: true
                        } else {
                        	error "未找到构建成品target/${JOB_BASE_NAME}.jar，请研发检查项目pom.xml的输出路径以及包名是否规范"
                        }
                    }
                }
            }
        }
        stage('部署') {
            steps {
                script {
                    sh '''
tee > start_up.sh <<EOF
#!/bin/bash
declare -A server_port_set
server_port_set=( ["ruoyi-auth"]="8090" ["ruoyi-system"]="8091" ["ruoyi-gateway"]="8080" )
server_port=\\${server_port_set["${JOB_BASE_NAME}"]}

[ -d /data/prog/project/${JOB_BASE_NAME} ] || mkdir -p  /data/prog/project/${JOB_BASE_NAME} 
project_jar_path=/data/prog/project/${JOB_BASE_NAME}/${JOB_BASE_NAME}.jar
update_jar_path=/data/update/${JOB_BASE_NAME}/${JOB_BASE_NAME}.jar

[ -f \\${project_jar_path} ] && { 
    echo "检测到旧的jar包，开始替换"
    backup_path=/data/backup/\\$(date +%F-%H-%M-%S)
    mkdir -p \\${backup_path}
    /bin/cp  -f \\${project_jar_path} \\${backup_path}/
    /bin/cp  -f \\${update_jar_path} \\${project_jar_path}
} || {
    /bin/cp  -f \\${update_jar_path} \\${project_jar_path}
}

jps |  grep ${JOB_BASE_NAME}.jar && {
    echo "开始kill ${JOB_BASE_NAME}.jar"
    kill -9  \\$(ps -ef | grep ${JOB_BASE_NAME}.jar | grep -v grep  |awk '{print \\$2}')
}
sleep 1
echo "开始部署 ${JOB_BASE_NAME} "
[ -d /data/logs/project/${JOB_BASE_NAME} ]  || mkdir -p /data/logs/project/${JOB_BASE_NAME}/
sleep 1
cd /data/prog/project/${JOB_BASE_NAME}/
nohup /data/prog/jdk1.8.0_271/bin/java \
-server -Xms500m -Xmx500m  \
-jar /data/prog/project/${JOB_BASE_NAME}/${JOB_BASE_NAME}.jar \
--server.port=\\${server_port} --spring.profiles.active=dev \
--spring.cloud.nacos.config.server-addr=192.168.50.203:8848 \
--spring.cloud.nacos.config.username=nacos \
--spring.cloud.nacos.config.password=nacos \
--spring.cloud.nacos.discovery.server-addr=192.168.50.203:8848 \
--spring.cloud.nacos.discovery.username=nacos \
--spring.cloud.nacos.discovery.password=nacos >> /data/logs/project/${JOB_BASE_NAME}/${JOB_BASE_NAME}-console.log 2>&1 & 
EOF
echo "部署完成 ${JOB_BASE_NAME} "
'''

            
                    // // 运行 Ansible 命令，并捕获退出码
                    def exitCode = sh(script: """
                        ansible ${PLATFORM}-${JOB_BASE_NAME} -m shell -a "mkdir -p /data/update/${JOB_BASE_NAME}"
                        ansible ${PLATFORM}-${JOB_BASE_NAME} -m copy -a "src=target/${JOB_BASE_NAME}.jar dest=/data/update/${JOB_BASE_NAME}/${JOB_BASE_NAME}.jar"
                        ansible ${PLATFORM}-${JOB_BASE_NAME} -m script -a "start_up.sh"
                    """, returnStatus: true)
                    
                    // 根据退出码进行处理
                    if (exitCode != 0) {
                        echo "Ansible 部署出现异常，请运维人员检查~！"
                        // 你可以在这里添加更多的错误处理逻辑
                        error "Ansible 部署出现异常，请运维人员检查~！"
                    } else {
                        echo "部署成功."
                    }
                }
            }
        }
    }
    post {
        always {
            script{
                wrap([$class: 'BuildUser']){
                    env.BUILD_USER = "${env.BUILD_USER_ID}" // 当次构建的用户 拼音
                    env.BUILD_USER_FIRST_NAME = "${env.BUILD_USER_FIRST_NAME}" // 当次构建用户 中文名字
                    env.BUILD_USER_EMAIL = "${env.BUILD_USER_EMAIL}" // 当次构建用户 邮箱

                    dingtalk (
                        robot: "${PLATFORM}",
                        type: 'MARKDOWN',
                        title: "[ ${JOB_BASE_NAME}  - 构建${currentBuild.result}提醒](${BUILD_URL})",
                        text: [
                            "# [ ${JOB_BASE_NAME}  - 构建${currentBuild.result}提醒](${BUILD_URL})",
                            "---",
                            "- 项目名称： ${JOB_BASE_NAME} ",
                            "- 构建编号： 第${BUILD_NUMBER}次构建",
                            "- 构建分支： ${BRANCH}",
                            "- 构建人： ${BUILD_USER_FIRST_NAME}",
                            "- 构建  Url ：${BUILD_URL}",
                            "- 任务持续时间: ${currentBuild.duration/1000}秒"
                        ]
                    )
                    currentBuild.displayName = "#${env.BUILD_NUMBER}-${env.PLATFORM}-${env.BRANCH}-${env.BUILD_USER_FIRST_NAME} "
                    currentBuild.description = "构建环境： ${env.PLATFORM}<br>构建分支： ${env.BRANCH}<br>构建人： ${env.BUILD_USER_FIRST_NAME}"
                }
            }
        }
    }
}